import tokenUtil from './tokenUtil.js'

const defConfig = {
	url: '',
	data: {},
	header: {
		'Content-Type': 'application/json'
	},
	method: "GET",
	timeout: 60000,
	dataType: "json",
	success: () => {},
	fail: () => {},
	complete: () => {}
}

/**
 * 请求前数据，token处理器
 */
const requestInterceptor = (_config) => {
	const header = tokenUtil.getTokenHeader()
	if (header) {
		Object.assign(_config.header, header)
	}
}

/**
 * @param {Object} 结果处理器
 */
const responseErrorHandel = (error) => {
	let message = `网络繁忙[${error.config?.url}]`
	if (error.code === 'ERR_NETWORK') {
		message = '网络异常，请检查网络连接情况！' + `[${error.config?.url}]`
	} else if (error.code === 'ECONNABORTED') {
		message = '请求超时，请检查网络连接情况！' + `[${error.config?.url}]`
	} else if (error.code === 500) {
		message = `网络繁忙[${error.msg}][${error.config?.url}]`
	}
	console.error(error)
	uni.showModal({
		title: '请求失败',
		content: message,
		showCancel: false,
	})
}

const send = (options) => {
	const _config = Object.assign(JSON.parse(JSON.stringify(defConfig)), options)
	requestInterceptor(_config)
	return new Promise((resolve, reject) => {
		_config.complete = (response) => {
			if (response.statusCode == 200) {
				const {
					data
				} = response
				// 正确请求，只有0才进行提示
				if (data.code == 0) {
					uni.showModal({
						title: '请求失败',
						content: data.msg || data.message || '请求失败',
						showCancel: false,
					})
				}
				resolve(data)
			} else {
				responseErrorHandel(response)
				reject({})
			}
		}
		uni.request(_config);
	})
}
/**
 * get请求
 */
const get = ({
	url,
	data
}) => {
	return send({
		url,
		data,
		method: "GET"
	})
}
/**
 * post请求
 */
const post = ({
	url,
	data
}) => {
	return send({
		url,
		data,
		method: "POST"
	})
}
/**
 * 文件上传
 */
const upload = ({
	url,
	filePath,
	data
}) => {
	return new Promise((resolve, reject) => {
		uni.uploadFile({
			url: url,
			filePath: filePath,
			name: 'file',
			header: {
				...tokenUtil.getTokenHeader()
			},
			formData: {
				...data
			},
			success: (res) => {
				resolve(res.data)
			},
			fail(res) {
				reject(res)
			}
		});
	})
}
export default {
	get,
	post,
	upload
}